package cn.globalph.housekeeper.data.source

import android.content.Context
import android.content.SharedPreferences
import cn.globalph.housekeeper.data.SP_USER_INFO
import cn.globalph.housekeeper.data.model.LoginModel
import cn.globalph.housekeeper.data.model.Profile
import com.google.gson.Gson

const val TOKEN = "token"
const val PROFILE = "profile"
class UserInfoPreferenceManager {
    companion object{
        private val gson = Gson()
        private fun preference(context: Context):SharedPreferences{
            return context.getSharedPreferences(SP_USER_INFO, Context.MODE_PRIVATE)
        }

        private fun edit(context: Context):SharedPreferences.Editor{
            return preference(context).edit()
        }

        fun getToken(context: Context):String?{
            return preference(context).getString(TOKEN,null)
        }

        fun getProfile(context: Context): Profile?{
            var temp = preference(context).getString(PROFILE,null)
            return gson.fromJson(temp,Profile::class.java)
        }

        fun updateInfo(context:Context,data:LoginModel?){
            if(data == null || data.token == null || data.profile == null){
                return
            }
            edit(context).putString(TOKEN,data.token).apply()
            edit(context).putString(PROFILE,gson.toJson(data.profile)).apply()
        }

        fun clearLoginData(context:Context){
            edit(context).putString(TOKEN,null).apply()
            edit(context).putString(PROFILE,null).apply()
        }
    }
}